﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenNETCF.Desktop.Communication;
using System.IO;
using DesktopDOHS.appData.Schemas;
using System.Xml.Serialization;
using ICSharpCode.SharpZipLib.Zip;

namespace DesktopDOHS
{
    public partial class frmPrincipal : Form
    {
        public RAPI m_rapi;

        public frmPrincipal()
        {
            InitializeComponent();

            // create our global RAPI object
            m_rapi = new RAPI();
        }

        private void sairToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void exportarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmExportFiles frmCF = new frmExportFiles();
            frmCF.MdiParent = this;
            frmCF.Show();
        }

        private void transferirPDAToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            { m_rapi.Connect(); }
            catch (Exception err)
            { MessageBox.Show("Not connected!" + err.Message); }
            
            // make sure we're connected
            if (!m_rapi.Connected)
                MessageBox.Show("Not connected!");
            else
            {
                string nomeLog = "Log" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".oms";
                //Copia o Log de Mensagens para o Desktop
                m_rapi.CopyFileFromDevice(Application.StartupPath + @"\Mensagens\tmp\" + nomeLog, @"\Program Files\PocketDOHS\Mensagens\MsgDOHSLog.oms", true);
                //Deserializa o Log do PDA
                TextReader trPDA = new StreamReader(Application.StartupPath + "\\Mensagens\\tmp\\" + nomeLog);
                XmlSerializer xs = new XmlSerializer(typeof(MensagemDOHS));
                MensagemDOHS msgDOHSLogPDA = (MensagemDOHS)xs.Deserialize(trPDA);
                trPDA.Close();
                //Deserializa o Log do Desktop
                TextReader trDesktop = new StreamReader(Application.StartupPath + "\\Mensagens\\Log\\MsgDOHSLog.oms");
                MensagemDOHS msgDOHSLogDesktop = (MensagemDOHS)xs.Deserialize(trDesktop);
                trDesktop.Close();
                //Percorre todo o log copiando os arquivos do PDA
                if (msgDOHSLogPDA.ExamesDOHS != null)
                {
                    int indice = msgDOHSLogPDA.ExamesDOHS.Count();
                    MensagemDOHSExamesDOHS msgPDA = new MensagemDOHSExamesDOHS();
                    for (int i = 0; i < indice; i++)
                    {
                        string msgPath = @"\Program Files\PocketDOHS\Mensagens\" + ((MensagemDOHSExamesDOHSMsgLog)msgDOHSLogPDA.ExamesDOHS[i].Item).Path;
                        msgPDA = msgDOHSLogPDA.ExamesDOHS[i];
                        //Verifica se Exame ja não Existe no Desktop
                        if (msgDOHSLogDesktop.ExamesDOHS != null)
                        {
                            foreach (MensagemDOHSExamesDOHS msgDesktop in msgDOHSLogDesktop.ExamesDOHS)
                            {
                                //Se ja existe msg no Desktop
                                if (msgDesktop.Equals(msgPDA))
                                {
                                    //Deseja Susbstituir??
                                    if (MessageBox.Show("O Exame\n\nData: " + msgPDA.Cabecalho.DataLevantamento +
                                        "\nExaminador: " + msgPDA.Cabecalho.CodExaminador +
                                        "\nLoc. Geo.: " + msgPDA.Cabecalho.LocGeo + "\n\nJá Existe no Sistema, deseja substituir?",
                                        "Atenção!", MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question,
                                        MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                                    {
                                        m_rapi.CopyFileFromDevice(Application.StartupPath + @"\Mensagens", msgPath, true);
                                    }
                                }
                                else
                                    m_rapi.CopyFileFromDevice(Application.StartupPath + @"\Mensagens", msgPath, true);
                            }
                        }
                        else
                            m_rapi.CopyFileFromDevice(Application.StartupPath + @"\Mensagens", msgPath, true);
                    }
                    if (MessageBox.Show("Deseja Limpar os Registros do PDA?",
                                        "Atenção!", MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question,
                                        MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        m_rapi.CopyFileToDevice(Application.StartupPath + "\\appData\\newLog\\MsgDOHSLog.oms", "\\Program Files\\PocketDOHS\\Mensagens\\MsgDOHSLog.oms", true);
                    }
                    MessageBox.Show("Mensagem copiada com Sucesso!");
                }
                else
                    MessageBox.Show("Não há registro de Exames no PDA!");
            }
        }

        private void importarExamesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ofdProcuraExame.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    ZipFile zip = new ZipFile(ofdProcuraExame.FileName);
                    Stream str = zip.GetInputStream(0);
                    XmlSerializer xs = new XmlSerializer(typeof(MensagemDOHS));
                    MensagemDOHS msgDOHSLogImport = (MensagemDOHS)xs.Deserialize(str);
                    
                    MessageBox.Show("Mensagens Importadas com Sucesso!", "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Mensagem nao importada, o arquivo deve estar corrompido!/n" + ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void cadastrarCodigosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmCadastroCodigo frmCC = new frmCadastroCodigo();
            frmCC.MdiParent = this;
            frmCC.Show();
        }

        private void cadastrarFichasToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PocketDOHS.MenuPrl frmLevantamento = new PocketDOHS.MenuPrl((this.Width / 2) - 120, (this.Height / 2) - 160);
            frmLevantamento.MdiParent = this;
            frmLevantamento.Show();
        }


    }
}
